#include "thread_pool.h"
#include <mysql/mysql.h>
#include <stdio.h>
#include <string.h>

extern MYSQL* conn;

void mkdirCommand(task_t * task)
{
    int userid = 0;
    int pwdid = 0;
    char filename[128] = {0};

    //得到userid
    int ret = getUserid(task->peerfd, &userid);
    if(ret){
        fprintf(stderr, "Get userid error\n");
        sendMsg(task->peerfd, MSG_TYPE_FAILURE, 
                "An error occurred while retrieving the user name.");
        return ;
    }
    printf("userid %d\n", userid);

    //查询得到pwdid
    char query[256] = {0};
    sprintf(query,
            "SELECT pwdid FROM t_user WHERE userid=%d", userid);
    ret = mysql_query(conn, query);
    MYSQL_RES * res = mysql_store_result(conn);
    MYSQL_ROW row = mysql_fetch_row(res);
    pwdid = atoi(row[0]);
    mysql_free_result(res);
    printf("pwdid: %d\n", pwdid);

    //得到文件名
    strcpy(filename, task->data);
    printf("filename: %s\n", filename);

    //查询当前目录下是否有相同文件名
    memset(query, 0, sizeof(query));
    sprintf(query,
            "SELECT fid FROM t_file WHERE owner_id=%d AND parent_id=%d AND filename='%s'",
            userid, pwdid, filename);
    mysql_query(conn, query);
    res = mysql_store_result(conn);
    int count = mysql_num_rows(res);
    mysql_free_result(res);
    printf("count: %d\n", count);

    //文件名已存在
    if(count == 1){
        fprintf(stderr, "Dupicated filename.\n");
        sendMsg(task->peerfd, MSG_TYPE_FAILURE, 
                "This dir already exists.");
        return ;
    }

    //向虚拟文件表中插入数据
    memset(query, 0, sizeof(query));
    sprintf(query,
            "INSERT INTO t_file(parent_id,filename,owner_id,md5,filesize,type) VALUES(%d,'%s',%d,'0',0,'d')",
            pwdid, filename, userid);
    mysql_query(conn, query);
    int affected_num = mysql_affected_rows(conn);
    if(affected_num == 1){
        printf("Insert successfully\n");
        sendMsg(task->peerfd, MSG_TYPE_SUCCESS, "Make dir successfully.");
        syslog(LOG_INFO, "User %d mkdir %s successfully.", userid, filename);
    } else {
        printf("Insertion failure.\n");
        sendMsg(task->peerfd, MSG_TYPE_FAILURE, 
                "An error occurred while inserting data.");
    }

}




//2期功能
void mkdirCommand1(task_t * task)
{
    char *message="create dir sucessful";
    char *message2="create dir failed";
    printf("execute mkdir commad");
    train_t t;
    memset(&t, 0, sizeof(t));
    if(mkdir(task->data,0777)==-1){
        strcpy(t.buff, message2);
        t.len = strlen(t.buff);
        sendn(task->peerfd, &t, t.len + 4);
        syslog(LOG_WARNING, "User execute MKDIR command: FAILED.");
    }else {
        strcpy(t.buff, message);
        t.len = strlen(t.buff);
        sendn(task->peerfd, &t, t.len + 4);
        syslog(LOG_INFO, "User execute MKDIR command: SUCCESSFUL.");
    }
}
